package com.zenithmind.gateway.service;

import com.zenithmind.gateway.config.ConfigurationManager;
import com.zenithmind.gateway.security.SecurityPolicyHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 默认网关服务实现
 * 专门负责网关的核心业务逻辑
 * 遵循单一职责原则：只负责网关服务的核心功能
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DefaultGatewayService implements GatewayService {
    
    private final ConfigurationManager configurationManager;
    private final SecurityPolicyHandler securityPolicyHandler;
    
    // 简单的统计计数器
    private final AtomicLong totalRequests = new AtomicLong(0);
    private final AtomicLong successfulRequests = new AtomicLong(0);
    private final AtomicLong failedRequests = new AtomicLong(0);

    @Override
    public HealthStatus checkHealth() {
        try {
            // 检查配置是否正常
            configurationManager.getServiceRoutes();
            
            // 检查安全策略是否正常
            securityPolicyHandler.shouldSkipAuth("/health");
            
            log.debug("网关健康检查通过");
            return HealthStatus.HEALTHY;
        } catch (Exception e) {
            log.error("网关健康检查失败", e);
            return HealthStatus.UNHEALTHY;
        }
    }

    @Override
    public GatewayStatistics getStatistics() {
        return new DefaultGatewayStatistics(
            totalRequests.get(),
            successfulRequests.get(),
            failedRequests.get()
        );
    }

    @Override
    public ValidationResult validateRequest(ServerHttpRequest request) {
        try {
            totalRequests.incrementAndGet();
            
            String path = request.getURI().getPath();
            
            // 基本的路径验证
            if (path == null || path.isEmpty()) {
                failedRequests.incrementAndGet();
                return new DefaultValidationResult(false, "请求路径为空");
            }
            
            // 检查是否是恶意路径
            if (path.contains("../") || path.contains("..\\")) {
                failedRequests.incrementAndGet();
                return new DefaultValidationResult(false, "检测到路径遍历攻击");
            }
            
            successfulRequests.incrementAndGet();
            return new DefaultValidationResult(true, "验证通过");
            
        } catch (Exception e) {
            failedRequests.incrementAndGet();
            log.error("请求验证失败", e);
            return new DefaultValidationResult(false, "验证过程中发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 默认网关统计信息实现
     */
    private static class DefaultGatewayStatistics implements GatewayStatistics {
        private final long totalRequests;
        private final long successfulRequests;
        private final long failedRequests;
        
        public DefaultGatewayStatistics(long totalRequests, long successfulRequests, long failedRequests) {
            this.totalRequests = totalRequests;
            this.successfulRequests = successfulRequests;
            this.failedRequests = failedRequests;
        }
        
        @Override
        public long getTotalRequests() {
            return totalRequests;
        }
        
        @Override
        public long getSuccessfulRequests() {
            return successfulRequests;
        }
        
        @Override
        public long getFailedRequests() {
            return failedRequests;
        }
        
        @Override
        public double getAverageResponseTime() {
            // 这里可以实现更复杂的响应时间统计
            return 0.0;
        }
    }
    
    /**
     * 默认验证结果实现
     */
    private static class DefaultValidationResult implements ValidationResult {
        private final boolean valid;
        private final String reason;
        
        public DefaultValidationResult(boolean valid, String reason) {
            this.valid = valid;
            this.reason = reason;
        }
        
        @Override
        public boolean isValid() {
            return valid;
        }
        
        @Override
        public String getReason() {
            return reason;
        }
    }
}
